package servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.Goods;
import service.GoodsManager;
import service.impl.GoodsManagerFactory;
import utils.Format;
import utils.UUIDGererator;

/**
 * Servlet implementation class AddGoodServlet
 */
public class AddGoodServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private GoodsManager manager;   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddGoodServlet() {
        super();
        manager = GoodsManagerFactory.getInstance();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//接受参数
		String gname = request.getParameter("gname");
		String price = request.getParameter("price");
		String count = request.getParameter("count");
		String gDate = request.getParameter("gDate");
		String address = request.getParameter("address");
		//校验
		boolean isError = false;
		if(gname.trim().length()<3){
			request.setAttribute("errorname", "name's length is less then 3");
			isError = true;
		}
		
		
		boolean verifyDate = Format.verifyDate(gDate);
		if(!verifyDate){
			request.setAttribute("errordate", "error date format");
			isError = true;
		}
		
		if(isError){
			request.setAttribute("gname", gname);
			request.setAttribute("price", price);
			request.setAttribute("count", count);
			request.setAttribute("gDate", gDate);
			request.setAttribute("address", address);
			request.getRequestDispatcher("addGoods.jsp").forward(request, response);
			return;
		}
		
		//类型转换
		int gcount = Integer.parseInt(count);
		double gprice = Double.parseDouble(price);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = sdf.parse(gDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//封装
		String gid = UUIDGererator.getUUID(); 
		Goods goods = new Goods(gid, gname, gprice, gcount, date, address);
		//调用业务
		int m = manager.addGoods(goods);
		//转发
		if(m>0){
			request.setAttribute("address", address);
			request.getRequestDispatcher("showGoods").forward(request, response);;
		}else{
			response.sendRedirect("error.jsp");
		}
	}

}
